<template>
  <div style="width: 680px; padding: 3px; margin: 5px;">
    <el-button type="primary" @click="state.dialogVisible = true">新建课程</el-button>
    <div class="card">
      <div v-for="item in state.courseList" :key="item.id">
        <el-card style="width:240px; margin: 3px;" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>{{item.name}}</span>
            </div>
          </template>
          <div class="courseBody">
            <div class="courseCover">
              <el-image style="width: 100px; height: 141px" :src="item.cover_front" fit="fill" @click="handleImageClick(item.id)" 
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              />
              <el-button type="success" size="small" text @click="state.coverDialogVisible = true">修改封面</el-button>
            </div>
              <div class="courseContent"> 
                <span>共{{ item.question_count }}道题</span>
                <span>作者：{{ item.owner_name }}</span>
                <span>
                  协作者：<br>
                    <template v-for="(name,index) in item.teamworker_name" :key="index">
                      {{ name }}<br>
                    </template>
                </span>
                <span>{{ item.add_time }}</span>
                <el-button v-if="localUser.username===item.owner_name" type="warning" size="small" @click="onClickAddCooperate(item.id)">邀请协作</el-button>
              </div>
          </div>
              
        </el-card>
      </div>
    </div>
    <el-dialog
      v-model="state.dialogVisible"
      title="输入课程名"
      width="500"       
    >
      <el-input v-model="inputCourseName" style="width: 240px" placeholder="输入课程名" />       
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="state.dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addCourse">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    
    <el-dialog
      v-model="state.dialogVisibleCooperation"
      title="邀请协作者"
      width="500" 
    >
    <div class="invite">
      <div class="invite-left">
        <div>
          <el-input v-model="state.inputPhone" style="width: 200px" placeholder="输入手机号码" :suffix-icon="Search" /> 
          <el-button type="primary" size="small" @click="onClickSearchUser"> 搜索 </el-button>
        </div>
        <div v-show="Object.keys(state.invitor).length > 0">
          <span>邀请他:</span>    
          <el-button type="warning" @click="onClickInviteHim()" text>{{ state.invitor.username }}</el-button>
        </div>
      </div>
      <div class="invite-right">
        <h2>已邀请人员</h2>
        <div v-for="(item,index) in state.cooperation_list" :key="index" class="invite-item">
          <el-text :type="getButtonType(index)" size="large" >{{ item.real_name }}</el-text>
          <el-tooltip
          class="box-item"
          effect="light"
          content="删除协作"
          placement="top"
          >
            <el-icon style="width: 1em; height: 1em; margin-right: 1px" @click="handleDeleteCooperation(item.id)">
              <Delete />
            </el-icon>
          </el-tooltip>
        </div>
      </div>
    </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="state.dialogVisibleCooperation = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  
</template>
<script setup>
  // 引入
import {reactive, onMounted, ref} from 'vue'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { Search, Delete } from '@element-plus/icons-vue'
import { localGet } from '@/utils'

let localUser = localGet('user_information')
const router = useRouter()
const store=useStore()
const inputCourseName = ref('')
const defaultProps = {
  children: 'children',
  label: 'label',
}  
// 通用变量
const state = reactive({
    nodeTree: [],
    dialogVisible: false,
    courseList: [],
    teamworker: [],
    dialogVisibleCooperation: false,
    invitor: {},
    inputPhone: '',
    selectCourse: 0,
    cooperation_list: [],
    coverDialogVisible:false,
})
const buttonTypeList = ['primary', 'success', 'info', 'warning', 'danger']
const getButtonType =(value)=>{ 
  // const value = Math.floor(Math.random() * 5)
  return buttonTypeList[value % buttonTypeList.length]
}
// 取消与该用户的合作
const handleDeleteCooperation = (user_id) => {
  let params = {
    node_id: state.selectCourse,
    user_id: user_id,
  }
  console.log('取消邀请者啦', params)
  axios.put(`/NodeModelViewSet/cancel_cooperation/`, params).then((res) => {
    console.log('查找结果：', res.data.results)
    if(res.code==200){
      ElMessage.success('取消协作成功')
      get_node_cooperation(state.selectCourse)
    }else
    if(res.code==1099){
      ElMessage.warning('找不到')
    }else
    if(res.code==1098){
      ElMessage.warning('无权操作')
    }
    else{
      console.log("提交失败", res)
    }       
  }).catch((error)=>{
    console.log("错误：", error)
  })
}
// 后台获取该课程所有的邀请者
const get_node_cooperation = (selectNode) => {
  console.log('获取该课程所有的邀请者', selectNode)
  let params = {
    node_id: selectNode,
  }
  axios.get(`/NodeModelViewSet/get_all_teamworker/`, {params}).then((res) => {
    console.log('查找结果：', res.data.results)
    if(res.code==200){
      ElMessage.success( '查找成功')
      state.cooperation_list = res.data.results 
    }else
    if(res.code==1099){
      ElMessage.warning( '找不到')
    }
    else{
      console.log("提交失败", res)
    }       
  }).catch((error)=>{
    console.log("错误：", error)
  })
}
// 点击邀请协作按钮
const onClickAddCooperate = (course)=>{
  if(course!==state.selectCourse){
    get_node_cooperation(course)
  }
  state.dialogVisibleCooperation = true
  state.selectCourse = course
}
// 点击搜索邀请者
const onClickSearchUser = ()=>{
  console.log('搜索邀请者')
  let params = {
    phoneNumber: state.inputPhone,
  }
  axios.get(`/UserModelViewSet/phone_number_exit/`, {params}).then((res) => {
    console.log('查找结果：', res.data.results)
    if(res.code==200){
      ElMessage.success( '查找成功')
      state.invitor = res.data.results 
    }else
    if(res.code==1099){
      ElMessage.warning( '找不到')
    }
    else{
      console.log("提交失败", res)
    }       
  }).catch((error)=>{
    console.log("错误：", error)
  })
}
// 确定邀请他
const onClickInviteHim = ()=>{
  console.log('发送后端邀请他', state.invitor.username)
  let params = {
      node: state.selectCourse,
      user: state.invitor.id,
  }
  axios.post(`/NodeCooperationViewSet/create_node_cooperation/`, params).then((res) => {
    if(res.code==200){
      ElMessage.success( '创建成功')     
      state.dialogVisibleCooperation = false;
      state.inputPhone = ''
      state.invitor = {}
      getAllCourse()
      get_node_cooperation(state.selectCourse)
    }else
    if(res.code==1099){
      ElMessage.warning( '服务器返回创建失败！')
    }
    else
    if(res.code==1098){
      ElMessage.warning( '该教师已经被邀请！')
    }
    else
    if(res.code==1097){
      ElMessage.warning( '这是作者，没必要邀请')
    }else
    if(res.code==1096){
      ElMessage.warning( '你的邀请能力已达极限，请升级VIP等级')
    }else
    if(res.code==1095){
      ElMessage.error( '你不是作者，无权邀请！')
    }
    else{
      console.log("提交失败", res)
    }       
  }).catch((error)=>{
    console.log("错误：", error)
  })
}
// 点击新建课程按钮
const addCourse = () => {
  console.log('新建课程啦')
  let params = {
      name: inputCourseName.value,
  }
  axios.post(`/NodeModelViewSet/create_node/`, params).then((res) => {
    if(res.code==200){
      ElMessage.success( '创建成功')
      state.nodeTree = res.data.results
      state.dialogVisible = false;
      getAllCourse()
    }else
    if(res.code==1099){
      ElMessage.warning( '标题不能为空！')
    }else
    if(res.code==1095){
      ElMessage.error( '你的新建课程能力已经达到极限，请升级VIP')
    }
    else{
      console.log("提交失败", res)
    }       
  }).catch((error)=>{
    console.log("错误：", error)
  })
}
// 点击节点事件
const handleNodeClick = (data) => {
  console.log(data)
}
// 获取所有的课程
const getAllCourse = () => {
  axios.get(`/NodeModelViewSet/get_all_course/`).then(res => {
    console.log("获取课程结果：",res)
    if (res.code==200){
      state.courseList= res.data.results
    }else
    if(res.code==1099){
      ElMessage.error('结果为空')
      return false
    }else{
      ElMessage.error('服务器错误')
    } 
  })
  .catch((error)=>{
    console.log("error:", error)
  })   
}

onMounted(()=>{    
  getAllCourse()
})
const handleImageClick=(id) => {
  console.log('跳转啦')
  store.commit('setNodeId', id)
  router.push(`/showQuestionPrivate`)
}
</script>

<style scoped>
.courseBody{
  display: flex;
  flex-direction: row;
  margin: 2px;
}
.courseContent{
  display: flex;
  flex-direction: column;
  padding:2px;
  font-size: smaller;
}
.card{
  display: flex;
  flex-wrap: wrap; 
  margin: 5px;
}
.card-item{
  width: 300px;
  margin: 5px;
  padding: 3px;
}
.invite {
  width:500px;
  display: flex;
  flex-flow:row, wrap;
  justify-content: space-between;
  align-items: center;
  /* margin: 5px;   */
}
.invite-right {
  width: 150px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 2px;
  margin: 5px;
}
.invite-item {
  display: flex;
  flex-flow: row, nowrap;
  margin: 6px;
  padding: 5px;
  justify-content: center;
  align-items: center;
}
.invite-left {
  width: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: 5px;
}
.courseCover {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}
</style>